package cn.fancy.sdk.service.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class QdHttpReq {
    
    private static String TAG = QdHttpReq.class.getSimpleName();
    
    public static String doRequest(String getUrl, Map<String, String> params) throws Exception {
        QdMakeLog.d(TAG, "doRequest with params");
        HttpURLConnection httpConn = null;
        String ret = null;
        try {
            URL url = new URL(getUrl);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(5000);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            
            StringBuffer buffer = new StringBuffer();
            for (Iterator<?> iter = params.entrySet().iterator(); iter.hasNext(); ) {
                Entry<?, ?> element = (Entry<?, ?>) iter.next();
                if (element.getKey() == null || element.getValue() == null) {
                    QdMakeLog.e(TAG, "HttpReq contains null key-value ");
                    continue;
                }
                buffer.append(URLEncoder.encode(element.getKey().toString(), "UTF-8"));
                buffer.append("=");
                buffer.append(URLEncoder.encode(element.getValue().toString(), "UTF-8"));
                buffer.append("&");
            }
            
            if (buffer.length() > 0) {
                buffer = buffer.deleteCharAt(buffer.length() - 1);
                QdMakeLog.e(TAG, buffer.toString());
            }
            byte[] b = buffer.toString().getBytes();
            OutputStream os = httpConn.getOutputStream();
            os.write(b);
            os.flush();
            os.close();
            
            int statusCode = httpConn.getResponseCode();
            if (statusCode == 200) {
                InputStream is = httpConn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
                String line;
                StringBuffer reBuf = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    reBuf.append(line);
                }
                ret = reBuf.toString();
                reader.close();
                is.close();
            } else {
                throw new Exception("Error occur when try to visit the url:"
                    + url.getPath() + " using HttpURLConnection");
            }
        } catch (Exception ex) {
            throw new Exception("Error caused by " + ex);
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
        return ret;
    }
    
    public static String md5(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            for (byte b : result) {
                int number = b & 0xff;
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
    
    public static String genUrlString(Map<String, String> Info) {
        StringBuffer buffer = new StringBuffer();
        try {
            for (Iterator<?> iter = Info.entrySet().iterator(); iter.hasNext(); ) {
                Entry<?, ?> element = (Entry<?, ?>) iter.next();
                if (element.getValue() == null || element.getKey() == null) {
                    continue;
                }
                buffer.append(URLEncoder.encode(element.getKey().toString(), "UTF-8"));
                buffer.append("=");
                buffer.append(URLEncoder.encode(element.getValue().toString(), "UTF-8"));
                buffer.append("&");
            }
            if (buffer.length() > 0) {
                buffer = buffer.deleteCharAt(buffer.length() - 1);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        ;
        String TurnString = buffer.toString();
        return TurnString;
    }
    
    /* 判断网络连接状态 */
    public static boolean isNetworkConnected(Context context) {
        boolean netStatus = false;
        try {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    netStatus = mNetworkInfo.isConnected();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return netStatus;
    }
}
